﻿namespace Admin.NET.Core.Btms;

/// <summary>
/// 血液库存操作管理
/// </summary>
public class KuCunManager : IScoped
{
    private readonly SqlSugarRepository<InvKuCun> _rep;

    public KuCunManager(SqlSugarRepository<InvKuCun> rep)
    {
        _rep = rep;
    }

    public ISugarQueryable<InvKuCun> Queryable
    {
        get
        {
            return _rep.AsQueryable();
        }
    }

    /// <summary>
    /// 批量新增
    /// </summary>
    public async Task<bool> InsertRangeAsync(List<InvKuCun> list, string caoZuo)
    {
        await AddOptRange(list, "新增", caoZuo);
        return await _rep.InsertRangeAsync(list);
    }

    /// <summary>
    /// 批量修改血液库存, 
    /// </summary>
    /// <param name="list">血液明细</param>
    /// <param name="mingCheng">传单据类型</param>
    /// <param name="neiRong">传备注或空</param>
    /// <returns></returns>
    public async Task<bool> UpdateKuCunZhuangTai(List<InvKuCun> list, string mingCheng, string neiRong = "")
    {
        await AddOptRange(list, mingCheng, neiRong);
        // TODO  修改为只修改库存状态
        return await _rep.UpdateRangeAsync(list);
    }

    /// <summary>
    /// 批量增加操作日志, 用于批量增加,修改库存(审核入库, 手工入库, 交叉配血, 临床发血等)
    /// </summary>
    protected async Task<bool> AddOptRange(List<InvKuCun> list, string mingCheng, string neiRong)
    {
        var currentUser = App.User == null || App.User.Identity.IsAuthenticated == false ? UserContext.Default : App.User;
        var caoZuoRen = currentUser?.FindFirst(ClaimConst.RealName)?.Value ?? "";
        var caoZuoRenId = currentUser?.FindFirst(ClaimConst.UserId)?.Value.ToLong() ?? 0;

        var listOpt = new List<OptXueYe>();
        foreach (var item in list)
        {
            listOpt.Add(new OptXueYe
            {
                kuCunId = item.Id,
                caoZuoHouZhuangTai = item.kuCunZhuangTai,

                mingCheng = mingCheng,
                neiRong = neiRong,

                caoZuoRen = caoZuoRen,
                caoZuoRenId = caoZuoRenId,
                caoZuoShiJian = DateTime.Now,
            });
        }

        var repOpt = _rep.ChangeRepository<SqlSugarRepository<OptXueYe>>();
        return await repOpt.InsertRangeAsync(listOpt);
    }

}
